package com.core.service.impl;

import com.alibaba.fastjson2.JSON;
import com.core.constant.RedisKey;
import com.core.domain.User;
import com.core.resp.AjaxResponse;
import com.core.dto.UserDetailsDto;
import com.core.service.LoginService;
import com.core.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : HUANG
 * @create : 2025/6/1 20:47
 * @function :
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResponse login(User user) throws Exception {
        log.info("用户登录请求: {}", user.getUsername());
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate == null) {
            log.warn("用户登录失败: {}, 原因: 用户名或密码错误", user.getUsername());
            throw new Exception("用户名和密码错误");
        }
        UserDetailsDto userDetailsDto = (UserDetailsDto) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(user.getUsername(), 30 * 60 * 1000L);
        ValueOperations<String, String> redisOps = redisTemplate.opsForValue();
        String userJson = JSON.toJSONString(userDetailsDto.getUser());
        redisOps.set(RedisKey.LOGIN_KEY + user.getUsername(), userJson, 30 * 60, TimeUnit.SECONDS);
        log.info("用户登录成功: {}", user.getUsername());
        return AjaxResponse.success(200, "登录成功", jwt);
    }
}
